<template>
  <a-modal :width="1000" v-model:visible="showCampaignPolicy" title="广告活动分时策略" :footer="$authPass('policy-targeting.batch-multiple-policy-type.save')" title-align="start" ok-text="保存" :mask-closable="false" @cancel="closedDialog" :ok-loading="submitLoading" :on-before-ok="saveData">
    <a-row class="detail-item">
      <a-col :span="8">
        <div class="flex">
          <p class="label">店铺：</p>
          <p class="val">{{ currentData.shopName }}</p>
        </div>
      </a-col>
      <a-col :span="9">
        <div class="flex">
          <p class="label">广告活动：</p>
          <div>
            <p class="val">{{ currentData.campaignName }}</p>
            <p class="info">{{ currentData.campaignId }}</p>
          </div>
        </div>
      </a-col>
      <a-col :span="5">
        <div class="flex">
          <p class="label">预算：</p>
          <p class="val">
            <span>{{ getCurrencySymbol() }}</span>
            <span>{{ currentData.budgetAmount }}</span>
          </p>
        </div>
      </a-col>
    </a-row>
    <a-row class="detail-item">
      <a-col :span="8">
        <div class="flex">
          <p class="label">状态：</p>
          <p class="val">{{ AdStatus[currentData.state] }}</p>
        </div>
      </a-col>
      <a-col :span="9">
        <div class="flex">
          <p class="label">组合名称：</p>
          <p class="val">{{ currentData.portfolioName }}</p>
        </div>
      </a-col>
      <a-col :span="5">
        <div class="flex">
          <p class="label">销售员：</p>
          <p class="val">{{ currentData.ownerName }}</p>
        </div>
      </a-col>
    </a-row>
    <a-row class="detail-item">
      <a-col :span="8">
        <div class="flex">
          <p class="label">类型：</p>
          <p class="val">{{ AdTypes[currentData.adType] }}</p>
        </div>
      </a-col>
      <a-col :span="9">
        <div class="flex">
          <p class="label">投放类型：</p>
          <p class="val">缺</p>
        </div>
      </a-col>
      <a-col :span="5">
        <div class="flex">
          <p class="label">竞价策略：</p>
          <p class="val">{{ DynamicBudgetStrategy[currentData.dynamicBudgetStrategy] || '未知' }}</p>
        </div>
      </a-col>
    </a-row>

    <a-tabs v-model:active-key="activeTab">
      <a-tab-pane key="BUDGET_POLICY" title="分时调整预算">
        <a-row style="margin-top: 20px">
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">
                <span class="warningColor">*</span>
                <span>策略模板：</span>
              </p>
              <a-select :disabled="!$authPass('policy-targeting.batch-multiple-policy-type.save')" v-model="editInfoMap[activeTab].selectPolicy" style="width: 200px" @change="changePolicy($event, 'BUDGET_POLICY')" placeholder="选择策略">
                <a-option v-for="item in editInfoMap[activeTab].policyList" :key="item.policyId" :value="item.policyId" :label="item.policyName" />
              </a-select>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">应用状态：</p>
              <a-select :disabled="!$authPass('policy-targeting.batch-multiple-policy-type.save')" v-model="editInfoMap[activeTab].state" style="width: 120px">
                <a-option :value="1" label="启用" />
                <a-option :value="0" label="暂停" />
              </a-select>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">生效日期：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <p v-else-if="!getPolicyDetail('BUDGET_POLICY').effectiveEndDate && !getPolicyDetail('BUDGET_POLICY').effectiveStartDate">一直有效</p>
              <p v-else>{{ getPolicyDetail('BUDGET_POLICY').effectiveStartDate }}~{{ getPolicyDetail('BUDGET_POLICY').effectiveEndDate }}</p>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">适用站点：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <p v-else>{{ getMarketplace('BUDGET_POLICY') }}</p>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="24">
            <div class="flex-c">
              <p class="label">原始预算：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <p v-else>
                <span style="margin-right: 10px">{{ PolicyBidType[getPolicyDetail('BUDGET_POLICY').budgetType] }}</span>
                <span class="highlight" v-if="getPolicyDetail('BUDGET_POLICY').budgetType === 'FIXED_BUDGET'">$ {{ getPolicyDetail('BUDGET_POLICY').fixedBudgetAmount }}</span>
              </p>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="24">
            <div class="flex">
              <p class="label">调整频率：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <div v-else>
                <ul class="flex-c rule-title">
                  <li>站点时间</li>
                  <li style="width: 400px">预算</li>
                </ul>
                <ul class="rule-list">
                  <li v-for="(role, i) in getPolicyDetail('BUDGET_POLICY').rules" :key="i" class="flex date-item">
                    <ul>
                      <li v-for="(item, j) in role.childs" :key="j" class="flex-c role-item">
                        <div style="width: 200px" class="flex-c">
                          <p style="width: 60px">
                            <span style="margin-right: 10px" v-if="!item.dayOfWeek || j === 0">{{ role.dayOfWeek }}</span>
                          </p>
                          <a-tag size="small">{{ item.date }}</a-tag>
                        </div>
                        <div style="width: 400px" class="flex-c-c">
                          <span style="margin-right: 5px; width: 90px">{{ PolicyRuleType[item.ruleType] }}</span>
                          <span style="width: 70px; text-align: left" v-if="item.ruleType === 'PERCENTAGE_INCREASE' || item.ruleType === 'PERCENTAGE_DECREASE'" class="highlight">{{ item.ruleAmount }}%</span>
                          <span style="width: 70px; text-align: left" class="highlight" v-else>${{ item.ruleAmount }}</span>
                          <span style="width: 60px; margin-left: 10px"><span v-if="item.ruleType != 'FIXED_VALUE'">预算上限</span></span>
                          <span style="width: 70px; text-align: left" class="highlight">${{ item.ruleAmountUpperLimit }}</span>
                        </div>
                      </li>
                    </ul>
                  </li>
                </ul>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane key="SWITCH_POLICY" title="分时启停">
        <a-row style="margin-top: 20px">
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">
                <span class="warningColor">*</span>
                <span>策略模板：</span>
              </p>
              <a-select :disabled="!$authPass('policy-targeting.batch-multiple-policy-type.save')" v-model="editInfoMap[activeTab].selectPolicy" style="width: 200px" @change="changePolicy($event, 'SWITCH_POLICY')" placeholder="选择策略">
                <a-option v-for="item in editInfoMap[activeTab].policyList" :key="item.policyId" :value="item.policyId" :label="item.policyName" />
              </a-select>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">应用状态：</p>
              <a-select :disabled="!$authPass('policy-targeting.batch-multiple-policy-type.save')" v-model="editInfoMap[activeTab].state" style="width: 120px">
                <a-option :value="1" label="启用" />
                <a-option :value="0" label="暂停" />
              </a-select>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">生效日期：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <p v-else-if="!getPolicyDetail('SWITCH_POLICY').effectiveEndDate && !getPolicyDetail('SWITCH_POLICY').effectiveStartDate">一直有效</p>
              <p v-else>{{ getPolicyDetail('SWITCH_POLICY').effectiveStartDate }}~{{ getPolicyDetail('SWITCH_POLICY').effectiveEndDate }}</p>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">适用站点：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <p v-else>{{ getMarketplace('SWITCH_POLICY') }}</p>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="24">
            <div class="flex-c">
              <p class="label">状态回调：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <p v-else>
                <span style="margin-right: 10px">生效时间结束后，将每个对象的状态调整为：{{ PolicyCallbackMap[getPolicyDetail('SWITCH_POLICY').isPolicyCallback] }}</span>
                <span class="highlight" v-if="getPolicyDetail('SWITCH_POLICY').isPolicyCallback == 1">{{ getPolicyDetail('SWITCH_POLICY').fixedCallbackValue == 'ENABLED' ? '启用' : '暂停' }}</span>
              </p>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="24">
            <div class="flex">
              <p class="label">调整频率：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <div v-else>
                <ul class="flex-c rule-title">
                  <li>站点时间</li>
                  <li>启停</li>
                </ul>
                <ul class="rule-list">
                  <li v-for="(role, i) in getPolicyDetail('SWITCH_POLICY').rules" :key="i" class="flex date-item">
                    <ul>
                      <li v-for="(item, j) in role.childs" :key="j" class="flex-c role-item">
                        <div style="width: 200px" class="flex-c">
                          <p style="width: 60px">
                            <span style="margin-right: 10px" v-if="!item.dayOfWeek || j === 0">{{ role.dayOfWeek }}</span>
                          </p>
                          <a-tag size="small">{{ item.date }}</a-tag>
                        </div>
                        <div style="width: 200px">
                          <span class="highlight">{{ item.ruleStatus === 'ENABLED' ? '启动' : '暂停' }}</span>
                        </div>
                      </li>
                    </ul>
                  </li>
                </ul>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane key="TARGETING_POLICY" title="分时调广告位">
        <a-row style="margin-top: 20px">
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">
                <span class="warningColor">*</span>
                <span>策略模板：</span>
              </p>
              <a-select :disabled="!$authPass('policy-targeting.batch-multiple-policy-type.save')" v-model="editInfoMap[activeTab].selectPolicy" style="width: 200px" @change="changePolicy($event, 'TARGETING_POLICY')" placeholder="选择策略">
                <a-option v-for="item in editInfoMap[activeTab].policyList" :key="item.policyId" :value="item.policyId" :label="item.policyName" />
              </a-select>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">应用状态：</p>
              <a-select :disabled="!$authPass('policy-targeting.batch-multiple-policy-type.save')" v-model="editInfoMap[activeTab].state" style="width: 120px">
                <a-option :value="1" label="启用" />
                <a-option :value="0" label="暂停" />
              </a-select>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">生效日期：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <p v-else-if="!getPolicyDetail('TARGETING_POLICY').effectiveEndDate && !getPolicyDetail('TARGETING_POLICY').effectiveStartDate">一直有效</p>
              <p v-else>{{ getPolicyDetail('TARGETING_POLICY').effectiveStartDate }}~{{ getPolicyDetail('TARGETING_POLICY').effectiveEndDate }}</p>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="flex-c">
              <p class="label">适用站点：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <p v-else>{{ getMarketplace('TARGETING_POLICY') }}</p>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="24">
            <div class="flex-c">
              <p class="label">基准竞价：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <p v-else>应用策略时的广告竞价</p>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="24">
            <div class="flex">
              <p class="label">调整频率：</p>
              <p v-if="!editInfoMap[activeTab].selectPolicy">--</p>
              <div v-else>
                <ul class="flex-c rule-title">
                  <li>站点时间</li>
                  <li>搜索结果顶部（首页）</li>
                  <li>商品页面</li>
                </ul>
                <ul class="rule-list">
                  <li v-for="(role, i) in getPolicyDetail('TARGETING_POLICY').rules" :key="i" class="flex date-item">
                    <ul>
                      <li v-for="(item, j) in role.childs" :key="j" class="flex-c role-item">
                        <div style="width: 200px" class="flex-c">
                          <p style="width: 60px">
                            <span style="margin-right: 10px" v-if="!item.dayOfWeek || j === 0">{{ role.dayOfWeek }}</span>
                          </p>
                          <a-tag size="small">{{ item.date }}</a-tag>
                        </div>
                        <div style="width: 200px">
                          <span style="margin-right: 10px">调整到</span>
                          <span class="highlight">{{ item.ruleTargetingTopAmount }}%</span>
                        </div>
                        <div style="width: 200px">
                          <span style="margin-right: 10px">调整到</span>
                          <span class="highlight">{{ item.ruleTargetingProductDetailAmount }}%</span>
                        </div>
                      </li>
                    </ul>
                  </li>
                </ul>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { getPolicyOption, getPolicyDetailById, batchAddPolicyTargeting, getCampaignPolicy } from '@/api/advert'
  import { AdStatus, AdTypes, PolicyRuleType, DynamicBudgetStrategy, PolicyBidType, PolicyWeekMap } from '../../types'
  import { marketPlaceList, currencySymbol } from '@/utils/globalData'
  import { Message } from '@arco-design/web-vue'
  onMounted(() => {
    getPolicyOptionList()
    getDefaultCampaignPolicy()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentData: {
      type: Object,
      default: () => {},
    },
    defaultSearchVal: {
      type: Object,
      default: () => {},
    },
    showType: {
      type: String,
      default: 'campaign', //campaign广告活动详情，adGroup广告组详情
    },
  })

  const showCampaignPolicy = ref(props.isShow)
  const editInfoMap = ref<any>({
    BUDGET_POLICY: {
      state: 1,
      policyList: [],
      policyDetail: {},
    },
    SWITCH_POLICY: {
      state: 1,
      policyList: [],
      policyDetail: {},
    },
    TARGETING_POLICY: {
      state: 1,
      policyList: [],
      policyDetail: {},
    },
  })
  const PolicyCallbackMap = {
    0: '原始状态',
    1: '固定状态',
    2: '不回调',
  }

  const activeTab = ref('BUDGET_POLICY')
  const submitLoading = ref(false)

  // 获取当前广告活动下的分时策略
  async function getDefaultCampaignPolicy() {
    const res: any = await getCampaignPolicy({ campaignId: props.currentData.campaignId })
    let policyList = res?.data || []
    policyList.forEach((el: any) => {
      editInfoMap.value[el.policyType].selectPolicy = el.id
      editInfoMap.value[el.policyType].state = el.policyTargetingState
      editInfoMap.value[el.policyType].policyDetail = el
      editInfoMap.value[el.policyType].policyDetail.rules = getRuleListArr(el.ruleInfos || [])
    })
  }
  // 显示货币符号
  function getCurrencySymbol() {
    let currency = marketPlaceList[props.currentData.marketplaceId]?.currency
    return currencySymbol[currency]
  }
  // 获取预算策略模板列表
  function getPolicyOptionList() {
    let arr = ['BUDGET_POLICY', 'SWITCH_POLICY', 'TARGETING_POLICY']
    arr.forEach((key: any) => {
      getPolicyOptionByType(key)
    })
  }
  async function getPolicyOptionByType(type: string) {
    const res: any = await getPolicyOption({
      marketplaceId: props.currentData.marketplaceId,
      policyType: type,
    })
    editInfoMap.value[type].policyList = res?.data || []
  }
  // 根据模板ID获取分时策略模板详情
  async function changePolicy(id: string, type: string) {
    if (!id) return
    const res: any = await getPolicyDetailById({ policyId: id })
    editInfoMap.value[type].policyDetail = res?.data || {}
    editInfoMap.value[type].policyDetail.rules = getRuleListArr(res?.data?.ruleInfos || [])
  }
  // 显示站点名称
  function getMarketplace(key: string) {
    let arr = editInfoMap.value[key]?.policyDetail?.applicableMarketplace?.split(',')
    let names = arr?.map((val: string) => marketPlaceList[val]?.code)
    return names?.join(',')
  }
  // 模板详情
  function getPolicyDetail(type: string) {
    return editInfoMap.value[type]?.policyDetail || {}
  }
  // 规则列表
  function getRuleListArr(ruleList: any) {
    let weekMap: any = {}
    ruleList.forEach((el: any) => {
      let week = PolicyWeekMap[el.dayOfWeek] || '每天'
      if (!weekMap[week]?.childs) {
        weekMap[week] = {
          dayOfWeek: week,
          childs: [],
        }
      }
      weekMap[week].childs.push({
        date: `${el.startTime}~${el.endTime}`,
        ...el,
      })
    })
    console.log(weekMap)
    return Object.values(weekMap)
  }
  // 关闭
  function closedDialog() {
    showCampaignPolicy.value = false
    emit('closed')
  }
  // 保存
  async function saveData() {
    let arr = ['BUDGET_POLICY', 'SWITCH_POLICY', 'TARGETING_POLICY']
    let list: Array<any> = []
    arr.forEach((key: any) => {
      let policyTargetings = [
        {
          adType: props.currentData.adType,
          campaignId: props.currentData.campaignId,
          portfolioId: props.currentData.portfolioId,
          shopId: props.currentData.shopId,
          state: editInfoMap.value[key].state,
        },
      ]
      if (editInfoMap.value[key]?.selectPolicy) {
        console.log(editInfoMap.value[key])
        list.push({
          policyId: editInfoMap.value[key].selectPolicy,
          policyType: key,
          targetingType: 'CAMPAIGN',
          policyTargetings: policyTargetings,
        })
      }
    })
    if (!list.length) {
      Message.error('请最少选择一个策略类型的模板')
      return false
    }
    const res: any = await batchAddPolicyTargeting(list)
    if (!res) return false
    Message.success('保存成功！')
    closedDialog()
    emit('success')
  }
</script>
<style lang="less" scoped>
  .detail-item {
    margin-bottom: 5px;
    height: 30px;
    line-height: 14px;
    .label {
      width: 80px;
      text-align: right;
    }
    .val {
      color: #666;
    }
    .info {
      font-size: 12px;
      color: #999;
    }
  }
  .label {
    width: 100px;
    text-align: right;
  }
  :deep(.arco-tabs-content) {
    height: calc(84vh - 300px);
    overflow-y: auto;
  }
  .rule-list {
    border: 1px solid var(--color-border);
    border-bottom: none;
    text-align: center;
    .date-item {
      border-bottom: 1px solid var(--color-border);
      padding-top: 5px;
    }
    .role-item {
      margin-bottom: 5px;
    }
  }
  .rule-title {
    border: 1px solid var(--color-border);
    border-bottom: none;
    li {
      width: 200px;
      text-align: center;
      padding: 3px 0;
    }
  }
</style>
